package service

import (
	"git.oschina.net/fanbuchi/redpack/database"
	"git.oschina.net/fanbuchi/redpack/domain"
	"git.oschina.net/fanbuchi/redpack/errors"
	"github.com/jinzhu/gorm"
)
type ProfileService struct {
}


func  (service*ProfileService)Create(params *domain.Profile)(*domain.Profile,error)  {
	//validate
	if params.AccountId==0 {
		 return nil,_error.ErrAccountNull
	}
	if params.NickName=="" || len(params.NickName)==0 {
		return nil,_error.ErrAccountNull
	}
	params.ID=0
	//
	has,err:=service.Query1ByAccountId(params.AccountId)

	if err == gorm.ErrRecordNotFound {
		err=database.Master().Create(params).Error
		if err!=nil {
			return nil,err
		}
		return params,nil
	}else if  err != nil {
		return nil,err
	}
	if has!=nil && has.ID!=0 {
		return nil,_error.ErrAccountExist
	}
	return nil,nil
}

func  (service*ProfileService)Delete1ById(id int64)(*domain.Profile,error)     {
	account:=domain.Profile{}
	account.ID=id
	err:=database.Master().Delete(account).Error
	if err!=nil {
		return nil,err
	}
	return &account,nil
}

func  (service*ProfileService)Update(params *domain.Profile)(*domain.Profile,error)     {
	err:=database.Master().Update(params).Error
	if err!=nil {
		return nil,err
	}
	return params,err
}

//根据非空字段查询账户
func  (service*ProfileService)Query1ByDomain(account *domain.Profile)(*domain.Profile,error)  {
	 err := database.Master().Omit("password").First(account).Error
	if err != nil {
		return nil,err
	}
	return account,nil
}

func  (service*ProfileService)Query1ByAccountId(accountId int64)(*domain.Profile,error)  {
	if accountId==0{
		return nil,_error.ErrAccountNull
	}
	var result domain.Profile
	err := database.Master().
		Where("account_id=?",accountId).
			First(&result).Error

	if err != nil {
		return nil,err
	}
	return &result,nil
}

//根据id查询一条数据
func  (service*ProfileService)Query1ById(id int64)(*domain.Profile,error)  {
	result:=new(domain.Profile)
	err := database.Master().Omit("password").First(result).Error
	if  err != nil {
		return nil,err
	}
	return result,nil
}

func  (service*ProfileService)Search(account *domain.Profile,page int,size int)([]*domain.Profile,error)  {
	accountList := make([]*domain.Profile, 0)
	pageable:=database.Page(page,size)
	err := database.Master().
		Scopes(pageable).
		Find(&accountList).Error
	if err!=nil {
		return nil,err
	}
	return accountList,nil
}




